import os, sys, tempfile, copy, re
from .mode import *
from .parameter import *
from .session import *
from subprocess import *

class process:
    def __init__(self, name, input_type = "S", output_type = "S", mode_count = None, description = ""):
        """
        A program can have modes w/ different parameters or just one set of parameters
        input_type and output_type can be:
            M   mono file
            S   stereo file
            A   anal file

            sndfile
            analfile
        """

        self.note = None
        self.name = name
        self.description = description
        self.modes = (mode_count and [0 for i in  range(mode_count+1)]) or [0]

        self.input_type = input_type
        self.output_type = output_type

        self.mode_count = mode_count

        self.mode = None
        self.parameters = []
        self.params = {}


    def set_note(self, note):
        self.note = note

    def __repr__(self):
        for p in params:
            print("%s\t%s\t%s\t%s" % (p.name, p.description, str(p.lower_limit), str(p.upper_limit)))

    def new_session(self, name, m = None):
        """Create a new session object with a reference to this process and a
        mode id.
        """
        return session(self, m)

    def add_mode(self, mode_number, *ps, mode_description = None, unused = None,  input_type = None, output_type = None):
        """Add a mode to the process.
        Returns mode."""

        """print(str(mode_number), ps)
        """

        if len(ps) is not 2:
            ps = (ps[0], "----")
            mode_description = ps[1]

        if not mode_number:
            mode_number = 0
            mode_description = ps[0]

        self.modes[mode_number] = mode(mode_description, input_type, output_type)

        m = self.modes[mode_number]

        m.add_parameters(ps[0])

        return m

    def set_mode(self, m):
        """Sets the process's mode.
        """
        if not m:
            return

        self.mode = m
        self.parameters = self.modes[m].parameters or []
        self.params = self.modes[m].params or {}

    def add_parameters(self, ps):
        """Adds a list of parameters to to the process.
        """
        self.parameters = ps

        for p in ps:
            self.params[p[0]] = parameter(*p)

    def __call__(self, mode = None):
        """Create new session and return it (at which time it will be executed).
        """
        mode = mode
        if mode is None:
            mode = 0
        self.set_mode(mode)
        return self.new_session(mode)
